package com.mcxx.modules.extremepoverty.service.impl;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.extremepoverty.service.ExSalvationCompleteService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberReadService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberHistoryWriteService;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dto.OrderListExcelDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderListExcelExDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderDetailEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.param.OrderListSearchParam;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderDetailWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilySalaryWriteService;
import com.mcxx.modules.miniSalvation.salary.service.write.SalaryChangeWriteService;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@TaTransactional
public class ExSalvationCompleteServiceImpl extends BaseService implements ExSalvationCompleteService {

    @Resource
    private ExportExcelService exportExcelService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private OrderDetailWriteService orderDetailWriteService;
    @Autowired
    private FamilyMemberHistoryWriteService familyMemberHistoryWriteService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private SalaryChangeWriteService salaryChangeWriteService;
    
    @Override
    public ExcelInfo exportExcelSave(OrderListSearchParam param, UserAccountVo accountVo){
        ExcelInfo excelInfo = null;
        QueryParamUtil.setBaseParamValue(param,accountVo);
        param.setBusinessType(Constant.BusinessCode.TEKUN);
        if("1".equals(param.getExportType())){
            
            
            
            List<OrderListExcelExDTO> list = orderReadService.exportListExTown(param);
            excelInfo = exportExcelService.exportOrgOpLogs(OrderListExcelExDTO.class,list,"特困乡镇已办信息.xls",
                    "特困人员救助供养乡镇已办列表","特困人员救助供养乡镇已办列表",false);
        }else if("2".equals(param.getExportType())){
            
            List<OrderListExcelExDTO> list = orderReadService.exportListExCounty(param);
            excelInfo = exportExcelService.exportOrgOpLogs(OrderListExcelExDTO.class,list,"特困区县已办信息.xls",
                    "特困人员救助供养区县已办列表","特困人员救助供养区县已办列表",false);
        }
        

        return excelInfo;
    }

    
    @Override
    public void backSalvationFinished(String orderId, String revokeReason, UserAccountVo userAccountVo){
        
        OrderEntity orderEntity = orderReadService.getOrderById(orderId);

        
        this.checkCountryRevoke(orderEntity);

        
        OrderEntity orderEntityForUpdate = new OrderEntity();
        orderEntityForUpdate.setBizState(Constant.BizStateNew.APPROVE_ING);
        orderEntityForUpdate.setOrderId(orderId);
        orderEntityForUpdate.setFamilyId(orderEntity.getFamilyId());
        orderEntityForUpdate.setState(Constant.BizStateNew.APPROVE_ING);
        orderEntityForUpdate.setCheckDate(null);
        orderEntityForUpdate.setCheckDept("");
        orderEntityForUpdate.setStartMonth("");
        orderEntityForUpdate.setEndMonth("");
        orderWriteService.updateForCountryRevoke(orderEntityForUpdate);

        
        OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
        orderDetailEntity.setOrderId(orderId);
        orderDetailEntity.setCheckType(Constant.CheckDatailStatus.revoke);
        orderDetailEntity.setBusinessStatus(Constant.RemarkOperType.COUNTY);
        orderDetailEntity.setCheckResult(Constant.AudtiOrApprovalResult.REVOKE);
        orderDetailEntity.setCheckOpinion(revokeReason);
        orderDetailEntity.setCheckPeople(userAccountVo.getUsername());
        orderDetailEntity.setCheckDate(new Date());
        orderDetailEntity.setOperator(userAccountVo.getLoginId());
        orderDetailEntity.setOrgId(userAccountVo.getOrgId());
        orderDetailEntity.setCreateBy(userAccountVo.getUserId());
        orderDetailWriteService.insertSalvationAudit(orderDetailEntity);

        
        familyMemberHistoryWriteService.deleteByOrderId(orderId);
        familySalaryWriteService.deleteSalaryByOrderId(orderId);
        
        salaryChangeWriteService.deleteBackByOrderId(orderId);

    }

    
    public void checkCountryRevoke(OrderEntity orderEntity){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        
        System.out.println(orderEntity.getState());
        if(!(Constant.BizStateNew.APPROVE_REFUSE.equals(orderEntity.getState()) || Constant.BizStateNew.APPROVE_YES.equals(orderEntity.getState()))){
            throw new BizException("-1", "只可以撤销审批完成的数据！");
        }

        
        if (Integer.parseInt(DateUtil.getMonthString().replaceAll("-", "")) - Integer.parseInt(sdf.format(orderEntity.getCheckDate())) >= 1 ) {
            throw new BizException("-1", "不能撤销当前月之前的审核记录");
        }

        
        String checkOtherOrder = orderReadService.getIdBySourceId(orderEntity.getSourOrderId());
        if(checkOtherOrder!=null &&  !checkOtherOrder.equals(orderEntity.getOrderId())) {
            throw new BizException("-1", "该数据已生成其他业务，不可撤销");
        }

        
        String orderId = orderReadService.getDataBySourceId(orderEntity.getOrderId());
        if(!StringUtils.isEmpty(orderId)){
            throw new BizException("-1", "该数据已生成其他业务，不可撤销");
        }

        
        if(orderEntity.getStartMonth()!=null && Constant.BizStateNew.APPROVE_YES.equals(orderEntity.getState())){
            fundPayReadService.verifyFundPayByOrderId(orderEntity.getBusinessType(), orderEntity.getCountyCode(),
                    orderEntity.getStandType(), orderEntity.getStartMonth(), orderEntity.getSupplyType(),
                    Constant.FundType.CAPITAL_FUND_PAY,orderEntity.getOrderId());
        }

        
        List<FamilyMemberEntity> list = familyMemberReadService.listHistroyByOrderId(orderEntity.getOrderId());
        if(list.size()==0) {
            list = familyMemberReadService.listByFamilyId(orderEntity.getFamilyId());
        }
        for (FamilyMemberEntity member:list) {
            
            String message = familyMemberReadService.checkIdcardForRevoke(member.getIdcard());
            if( message!= null) {
                throw new BizException("-1", "成员["+member.getIdcard()+"]已生成其他业务，该业务不可撤销！");
            }
        }
    }
}
